package com.keyware.kd.service.impl.user;

import com.keyware.kd.controller.user.UserController;
import com.keyware.kd.exception.RemoteCallFailedException;
import com.keyware.kd.repository.entity.UserSecret;
import com.keyware.kd.repository.entity.user.User;
import com.keyware.kd.service.itf.auditlog.AuditLogService;
import com.keyware.kd.service.itf.message.MessageService;
import com.keyware.kd.service.itf.number.NumberBuilderService;
import com.keyware.kd.service.itf.user.UserService;
import com.keyware.kd.service.itf.user.UserServiceRemove;
import com.keyware.kd.service.itf.usersecret.UserSecretService;
import com.keyware.kd.task.util.AjaxMessage;
import com.keyware.kd.utils.Constant;
import com.keyware.kd.utils.HttpClientUtil;
import com.keyware.kd.utils.RemoteProperties;
import com.keyware.utils.*;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserServiceRemoveImpl implements UserServiceRemove {
    public static Logger logger = Logger.getLogger(UserServiceRemoveImpl.class);

    @Autowired
    private UserService userService;
    @Autowired
    private UserSecretService userSecretService;

    @Autowired
    private NumberBuilderService numberBuilderService;
    @Resource
    private AuditLogService auditLogService;

    @Autowired
    private MessageService messageService;

    @Transactional(rollbackFor = {RemoteCallFailedException.class, Exception.class})
    @Override
    public AjaxMessage add(AjaxMessage ajaxMessage, User user, HttpServletRequest request) {
        List<User> selectByUserNumber = userService.selectByUserNumber(user.getUserNumber());
        if (selectByUserNumber.size() > 0) {
            ajaxMessage.setCode("0");
            ajaxMessage.setMessage("员工编号已存在");     // 修改提示信息与内容保持一致，‘用户编号已存在’--‘员工编号已存在’
            return ajaxMessage;
        }

        Integer userCount = Constant.userCount;
        //如果是0的话则不做验证
        if (0 != userCount) {
            List<User> selectAll = userService.selectAll(null);
            if (userCount <= selectAll.size()) {
                ajaxMessage.setCode("0");
                ajaxMessage.setMessage("当前版本只允许新建" + Constant.userCount + "个用户");
                return ajaxMessage;
            }
        }

        user.setPasswordOld(user.getPassword());
        user.setPassword(EncryptUtil.md5(user.getPassword()));
        user.setUserCreationTime(DateUtils.getDate());
        user.setUserPwdModifTime(DateUtils.getDate("yyyy-MM-dd HH:mm"));
        user.setUserStatus((long) 0);
        user.setUserLock((long) 0);
        user.setLogout((long) 0);
        user.setId(IdGenerator.uuid32());
//			int sort=userService.count()+1;
        String sort = DateUtils.getDateTimeInt();
        user.setSort(sort);
        //判断为空的数据使用数据库默认值
        userService.insertSelective(user);
        //数据库中编号+1
        numberBuilderService.updateNumber("user_code");
        //保存用户的日志
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("userName");
        String comments = userName + "添加了用户" + user.getUserName();
        auditLogService.insertLog("添加人员", "用户列表", comments, request);
        String numCode = getUser_idFormSession(request, "customCode");
        if (numCode != null && numCode.equals(ProjectIdentNew.tianjin712)) {
            User safeUser = userService.selectUserByUserId("safesecret");
            messageService.insertMessage("添加用户" + user.getUserName() + "", "用户管理", null, safeUser.getId(), "", "0", "K");
        }
        if (numCode != null && (numCode.equals(ProjectIdentNew.siyuan17suo) || numCode.equals(ProjectIdentNew.guiyangshiyuan))) {
            //保存人员密级信息
            UserSecret userSecret = new UserSecret();
            userSecret.setId(user.getId());
            userSecret.setSecret(user.getSecret());
            userSecretService.insertSelective(userSecret);
        }
        //远程调用

        /**
         *### 返回结果
         *
         * | 参数名称  | 参数说明                    | 类型    |
         * | --------- | --------------------------- | ------- |
         * | code      | 返回状态码（1 成功  0失败） | Integer |
         * | data      | 返回数据                    | Object  |
         * | msg       | 返回信息                    | String  |
         * | success   | 操作是否成功                | Boolean |
         * | timestamp | 时间戳                      | Long    |
         *
         * ```json
         * {
         * 	"code": 1,
         * 	"data": {},
         * 	"msg": "操作成功",
         * 	"success": true,
         * 	"timestamp": 1715534400000
         * }
         */
//        if (!StringUtils.isEmpty(RemoteProperties.API_URL)) {
//            String response = null;
//            try {
//                response = HttpClientUtil.doGet(RemoteProperties.API_URL + "?userId=" + user.getId() + "&type=add");
//                logger.info("【远程调用响应】：" + response);
//            } catch (Exception e) {
//                throw new RemoteCallFailedException("远程调用异常", e);
//            }
//            if (StringUtils.isEmpty(response)) {
//                throw new RemoteCallFailedException("远程服务返回失败状态");
//
//            }
//            JSONObject json = new JSONObject(response);
//
//            if (!"1".equals(String.valueOf(json.get("code")))) {
//                throw new RemoteCallFailedException("远程服务返回失败状态");
//            }
//
//        }
        ajaxMessage.setCode("1");
        ajaxMessage.setMessage("保存成功");
        return ajaxMessage;
    }

    @Transactional(rollbackFor = {RemoteCallFailedException.class, Exception.class})
    @Override
    public void delete(String userName,HttpServletRequest request) {
        List<String> listId= IdComposeListUtil.listId(request);

        String userNames = "";
        for(String id : listId){
            User u = userService.selectByPrimaryKey(id);
            if("".equals(userNames)){
                userNames = u.getUserName();
            }else{
                userNames += "," + u.getUserName();
            }

        }
        userService.deleteByPrimaryKey(listId);
        //删除人员日志
        String comments = userName + "删除了用户" + userNames;
        auditLogService.insertLog("删除人员", "用户列表", comments, request);
        String  numCode = getUser_idFormSession(request,"customCode");
        if(numCode != null && numCode.equals(ProjectIdentNew.tianjin712)){
            User safeUser = userService.selectUserByUserId("safesecret");
            messageService.insertMessage("删除用户"+userNames+"", "用户管理", null,safeUser.getId(), "", "0","K");
        }
        //删除人员密级信息
        if(numCode != null && (numCode.equals(ProjectIdentNew.siyuan17suo) || numCode.equals(ProjectIdentNew.guiyangshiyuan))){
            userSecretService.deleteByPrimaryKey(listId);
        }
        //删除  角色 用户 关联关系表
        for(String id : listId){
            userService.deleteUserRoleByUserId(id);
            //deleteRemoteUser
            deleteRemoteUser(id);
        }



    }

    public String getUser_idFormSession(HttpServletRequest request, String user_id) {
        return (String) request.getSession().getAttribute(user_id);
    }

    void deleteRemoteUser(String id){
        if (!StringUtils.isEmpty(RemoteProperties.API_URL)) {
            String response = null;
            try {
                response = HttpClientUtil.doGet(RemoteProperties.API_URL + "?userId=" + id + "&type=del");
            } catch (Exception e) {
                throw new RemoteCallFailedException("远程调用异常", e);
            }
            if (StringUtils.isEmpty(response)) {
                throw new RemoteCallFailedException("远程服务返回失败状态");

            }
            JSONObject json = new JSONObject(response);
            if (!"1".equals(String.valueOf(json.get("code")))) {
                throw new RemoteCallFailedException("远程服务返回失败状态");
            }

        }
    }



}
